﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using IntroduceCompany.Singleton;
using IntroduceCompany.Util;
using System.IO;
using System.ComponentModel.DataAnnotations;
using System.Data.Linq;

namespace IntroduceCompany.Models
{
    public class AlbumView_Validation
    {
        //[System.ComponentModel.DataAnnotations.MetadataType(typeof(IntroduceCompany.Models.AlbumView_Validation))]  put in Article class of linq

        [Required(ErrorMessage = "Tiêu đề Không được để trống")]
        public string AlbumTitle { get; set; }

    }

    public class AlbumModels
    {
        private ThumbnailClass _thumbnailClass = new ThumbnailClass();
   #region BackEnd_Album
        /// <summary>
        /// get all album()
        /// </summary>
        /// <returns> IQueryable of ArticleListView  </returns>
        public IQueryable<AlbumView> GetAlbums(String languageID, String amount)
        {
            if (amount == "")
            {
                if (languageID == ConstantClass.markViewAllLanguage)
                {
                    return DataSingleton.GetInstance().AlbumViews.OrderByDescending(u => u.AlbumID);
                }
                else
                {
                    return DataSingleton.GetInstance().AlbumViews.Where(u => u.LanguageID == languageID).OrderByDescending(u => u.AlbumID);
                }
            }
            else {
                int _amount = Convert.ToInt16(amount);
                if (languageID == ConstantClass.markViewAllLanguage)
                {
                    return DataSingleton.GetInstance().AlbumViews.OrderByDescending(u => u.AlbumID).Take(_amount);
                }
                else
                {
                    return DataSingleton.GetInstance().AlbumViews.Where(u => u.LanguageID == languageID).OrderByDescending(u => u.AlbumID).Take(_amount);
                }
            }
        }

        /// <summary>
        /// change  album visibility
        /// </summary>
        /// <param name="albumID"></param>
        /// <param name="albumVisible"></param>
        internal void ChangeAlbumVisible(int albumID, bool albumVisible)
        {
            Album album = DataSingleton.GetInstance().Albums.SingleOrDefault(u => u.AlbumID == albumID);
            album.AlbumVisible = (!albumVisible);
            DataSingleton.GetInstance().Albums.Context.SubmitChanges();
        }

        internal int AlbumCreate(AlbumView _NewOneAlbum)
        {
            int re = DataSingleton.GetInstance().sp_AlbumInsert(_NewOneAlbum.AlbumPhoto, _NewOneAlbum.Username);

            return re;
        }

        internal bool Album_L_Create(int albumMaxID, String languageID, string title, string des)
        {
            try
            {
                DataSingleton.GetInstance().sp_Album_L_Insert(albumMaxID, languageID, title.Trim(), des.Trim());

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }
            return true;
        }


        /// <summary>
        /// Get all album
        /// </summary>
        /// <param name="albumID"></param>
        /// <param name="languageID"></param>
        /// <returns></returns>
        internal AlbumView GetAlbumByAlbumIDAndLanguageID(int albumID, String languageID)
        {
            return DataSingleton.GetInstance().AlbumViews.SingleOrDefault(u => u.AlbumID == albumID && u.LanguageID == languageID);
        }


        /// <summary>
        /// Get all visible album 
        /// </summary>
        /// <param name="albumID"></param>
        /// <param name="languageID"></param>
        /// <returns></returns>
        internal AlbumView GetAlbumByAlbumIDAndLanguageID_Frontend(int albumID, String languageID)
        {
            return DataSingleton.GetInstance().AlbumViews.SingleOrDefault(u => u.AlbumID == albumID && u.LanguageID == languageID && u.AlbumVisible == true);
        }


        internal Album GetAlbumByID(int albumID)
        {
            return DataSingleton.GetInstance().Albums.SingleOrDefault(u => u.AlbumID == albumID);
        }

        /// <summary>
        /// Update album information into database
        /// </summary>
        /// <param name="_EditedAlbumView"></param>
        /// <returns></returns>
        internal bool AlbumEdit(AlbumView _EditedAlbumView)
        {
            try
            {
                Album _OldAlbum = DataSingleton.GetInstance().Albums.SingleOrDefault(u => u.AlbumID == _EditedAlbumView.AlbumID);
                //     _OldAlbum.AlbumPhoto = _EditedAlbumView.AlbumPhoto;
                _OldAlbum.UserName = _EditedAlbumView.Username;
                _OldAlbum.AlbumDate = DateTime.Now;
                DataSingleton.GetInstance().Albums.Context.SubmitChanges();

                Album_L _OldAlbum_L = DataSingleton.GetInstance().Album_Ls.SingleOrDefault(u => u.AlbumID == _EditedAlbumView.AlbumID 
                    && u.LanguageID == _EditedAlbumView.LanguageID);
                _OldAlbum_L.AlbumTitle = _EditedAlbumView.AlbumTitle.Trim();
                _OldAlbum_L.AlbumDescription = _EditedAlbumView.AlbumDescription.Trim();

                DataSingleton.GetInstance().Album_Ls.Context.SubmitChanges();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_EditedAlbumView"></param>
        internal void UpdateAlbumThumbnail(AlbumView _EditedAlbumView)
        {
            Album _OldAlbum = DataSingleton.GetInstance().Albums.SingleOrDefault(u => u.AlbumID == _EditedAlbumView.AlbumID);

            _OldAlbum.AlbumPhoto = _EditedAlbumView.AlbumPhoto;
            _OldAlbum.UserName = _EditedAlbumView.Username;
            _OldAlbum.AlbumDate = DateTime.Now;

            DataSingleton.GetInstance().Albums.Context.SubmitChanges();
        }

        internal void AlbumDelete(int albumID, string path)
        {
            Album album = DataSingleton.GetInstance().Albums.SingleOrDefault(u => u.AlbumID == albumID);
            DataSingleton.GetInstance().Albums.DeleteOnSubmit(album);
            DataSingleton.GetInstance().SubmitChanges();

            /// delete image and thumbnail folder
            string localfile = path + "/album-" + albumID;
            string localfile2 = path + "/album-" + albumID + "/photo";
            string localfile3 = path + "/album-" + albumID + "/photo/thumbnail";
            //DirectoryInfo directory = new DirectoryInfo(localfile);
            //System.Threading.Thread.Sleep(100);
            //directory.Delete(true);

            DirectoryInfo dir = new DirectoryInfo(localfile);
            DirectoryInfo dir2 = new DirectoryInfo(localfile2);
            DirectoryInfo dir3 = new DirectoryInfo(localfile3);

            //xoa folder thumbnail và hinh
            if (Directory.Exists(localfile3))
            {
                foreach (FileInfo files in dir3.GetFiles())
                {
                    files.Delete();
                }
                System.Threading.Thread.Sleep(100);
                dir3.Delete(true);
            }

            //xoa folder photo và hình
            if (Directory.Exists(localfile2))
            {
                foreach (FileInfo files in dir2.GetFiles())
                {
                    files.Delete();
                }

                System.Threading.Thread.Sleep(100);
                if (!Directory.Exists(localfile3))
                {
                    dir2.Delete(true);
                }
            }

            //xoa folder album-ID và hình
            if (Directory.Exists(localfile))
            {
                foreach (FileInfo files in dir.GetFiles())
                {
                    files.Delete();
                }

                System.Threading.Thread.Sleep(100);
                if (!Directory.Exists(localfile3))
                {
                    dir.Delete(true);
                }
            }
        }

        internal void UploadImageAlbumDetail(int albumID, IEnumerable<HttpPostedFileBase> fileToUpload, string path)
        {
            string uploadPath1 = path + "album-" + albumID + "/photo/";
            string uploadPath2 = path + "album-" + albumID + "/photo/thumbnail/";
            //Guid guid;
            string name = "";
            string fullName = "";
            string fileExtension = "";

            string albumSeoUrl = DataSingleton.GetInstance().Album_Ls.SingleOrDefault(a => a.AlbumID == albumID && a.LanguageID == ConstantClass.mainLanguageID)
                .AlbumSeoUrl;

            foreach (var file in fileToUpload)
            {
                //guid = System.Guid.NewGuid();
                name = albumSeoUrl + "-" + DateTime.Now.Ticks;
                name = name.Length > 190 ? name.Substring(0, 190) : name;

                fileExtension = Path.GetExtension(file.FileName).ToLower().Trim();
                fullName = name + fileExtension;

                Image imageRecord = new Image();

                imageRecord.UserName = "admin"; //sẽ thay đổi khi có login
                imageRecord.AlbumID = albumID;
                imageRecord.ImageName = fullName;

                DataSingleton.GetInstance().Images.InsertOnSubmit(imageRecord);
                
                _thumbnailClass.UploadImage1(file, uploadPath1, 600, file.FileName, name);
                _thumbnailClass.UploadImage1(file, uploadPath2, 100, file.FileName, name);
            }
            DataSingleton.GetInstance().SubmitChanges();
        }

        internal void AlbumImageDelete(int imageID, String path)
        {
            Image tempImage = DataSingleton.GetInstance().Images.SingleOrDefault(u => u.ImageID == imageID);
            DataSingleton.GetInstance().Images.DeleteOnSubmit(tempImage);
            DataSingleton.GetInstance().SubmitChanges();

            string path1 = path + "/photo/";
            string path2 = path + "/photo/thumbnail/";

            if (tempImage.ImageName != "")
            {
                string LocalFile = path1 + tempImage.ImageName;
                if (File.Exists(LocalFile))
                    File.Delete(LocalFile);

                LocalFile = path2 + tempImage.ImageName;
                if (File.Exists(LocalFile))
                    File.Delete(LocalFile);
            }

        }

   #endregion

//////////////////////////////////////////////////////////////////////

   #region FrontEnd_Album

        internal int Frontend_GetTotalRowsOneLanguage(String languageID)
        {
            return DataSingleton.GetInstance().AlbumViews.Where(u => u.LanguageID == languageID && u.AlbumVisible == true).Count();
        }

        /// <summary>
        /// use in paging albums in frontend.
        /// </summary>
        /// <param name="languageID"></param>
        /// <param name="pageIndex"></param>
        /// <param name="step"></param>
        /// <returns></returns>
        internal IQueryable<AlbumView> Frontend_GetOnePageAlbum(string languageID, string pageIndex, int step)
        {
            int startRowIndex = (Convert.ToInt16(pageIndex) - 1) * step;
            return DataSingleton.GetInstance().AlbumViews.Where(u => u.LanguageID == languageID && u.AlbumVisible == true).OrderByDescending(u => u.AlbumID).Skip(startRowIndex).Take(step);
        }

        /// <summary>
        /// get album menu ID by SEO URL in MenuList_L table
        /// </summary>
        /// <param name="menu_SEO_URL"></param>
        /// <returns></returns>
        //internal string GetAlbumMenuID_By_SEO_URL(string menu_SEO_URL)
        //{
        //    return DataSingleton.GetInstance().MenuList_Ls.SingleOrDefault(u => u.MenuSeoUrl == menu_SEO_URL).MenuListID.ToString();
        //}

        /// <summary>
        /// get album menu name SEO URL  by Album MenuID and LanguageID in MenuList_L table
        /// </summary>
        /// <param name="albumMenuID"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        //internal string GetAlbumMenuSEO_URL_By_AlbumMenuID_LanguageID(string albumMenuID, string languageID)
        //{
        //    return DataSingleton.GetInstance().MenuList_Ls.SingleOrDefault(u => u.MenuListID == Convert.ToInt16(albumMenuID) && u.LanguageID == languageID).MenuSeoUrl;
        //}

        /// <summary>
        /// get album ID by SEO URL. If seoUrl is not existed, it will return 0
        /// </summary>
        /// <param name="album_SEO_URL"></param>
        /// <returns></returns>
        internal int GetAlbumID_By_SEO_URL(string album_SEO_URL)
        {
            try
            {
                return DataSingleton.GetInstance().Album_Ls.SingleOrDefault(u => u.AlbumSeoUrl == album_SEO_URL).AlbumID;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return 0;
            }
        }

        /// <summary>
        /// get album name SEO URL by albumId and languageID 
        /// </summary>
        /// <param name="albumID"></param>
        /// <param name="languageID"></param>
        /// <returns></returns>
        internal string GetAlbumSEO_URL_By_AlbumID_LanguageID(int albumID, string languageID)
        {
            return DataSingleton.GetInstance().Album_Ls.SingleOrDefault(u => u.AlbumID == albumID && u.LanguageID == languageID).AlbumSeoUrl;
        }

        internal bool CheckAlbum_WithLanguage(int albumID, string languageID)
        {
            return DataSingleton.GetInstance().Album_Ls.Any(u => u.AlbumID == albumID && u.LanguageID == languageID);
        }
   #endregion



        /// <summary>
        /// Get all Image in album
        /// </summary>
        /// <param name="albumID"></param>
        /// <returns></returns>
        internal IQueryable<Image> GetAlbumImages(int albumID)
        {
            return DataSingleton.GetInstance().Images.Where(u => u.AlbumID == albumID);
        }
    }
}